//
//  WBImgListHandle.m
//  UILbrary
//
//  Created by Apple on 2023/3/2.
//  Copyright © 2023 mac. All rights reserved.
//

#import "WBImgListHandle.h"
#import "WBImagesContainView.h"
#import "PickImageHandle.h"
@import PhotosUI;

#define MAX_IMG_COUNT 5

@interface WBImgListHandle()

@property (nonatomic, strong) WBImagesContainView *p_view;
@property (nonatomic, strong) WBAddImgView *addImg;
@property (nonatomic, strong) PickImageHandle *pickImgHandle;
@property (nonatomic, strong) NSArray <UIView *>*imgViewList;
@property (nonatomic, strong) NSArray <NSString *>*imgIdList;
@property (nonatomic, strong) NSArray <NSData *>*imgDataList;
@property (nonatomic, strong) NSArray <NSString *>*imgBase64List;

@end




@implementation WBImgListHandle

//MARK: - system

- (void)dealloc
{
    NSLog(@"%@ %s",NSStringFromClass([self class]), __func__);
}


- (instancetype)init
{
    self = [super init];
    if(self){
        [self p_initConfig];
    }
    return self;
}

//MARK: - FBCompleteProtocol

- (void)completeHandle:(NSObject *)obj
{
    if(!self.imgIdList ||
       self.imgIdList.count <= 0){
        [self p_showTipEmptImgList];
        return;
    }
    
    dispatch_group_t group = dispatch_group_create();

    PHFetchResult<PHAsset *> * result = [PHAsset fetchAssetsWithLocalIdentifiers:self.imgIdList options:nil];
    [result enumerateObjectsUsingBlock:^(PHAsset * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if(!obj) return;
        dispatch_group_enter(group);
        [self p_requestImgDataWithAsset:obj complete:^{
            dispatch_group_leave(group);
        }];
    }];
    
    dispatch_group_notify(group, dispatch_get_main_queue(),^{
        [self p_convertImgDataTobase64Complete:^{
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.nextStep completeHandle:[self netRequestParam:obj]];
                [self p_resetData];
            });
        }];
    });
}

//MARK: - private

- (void)p_resetData
{
    self.imgDataList = @[];
    self.imgBase64List = @[];
}

- (NSDictionary *)netRequestParam:(NSObject *)obj
{
    NSDictionary *tmp_dic = (NSDictionary *)obj;
    if(!tmp_dic){
        tmp_dic = @{};
    }
    NSMutableDictionary *mutableDic = [tmp_dic mutableCopy];
    [mutableDic addEntriesFromDictionary:tmp_dic];
    mutableDic[@"imgBase64Array"] = self.imgBase64List;
    
    return [mutableDic copy];
}

- (void)p_convertImgDataTobase64Complete:(void(^)(void))complete{

    dispatch_queue_t queue = dispatch_queue_create("com.jinxun.serialqueue", DISPATCH_QUEUE_SERIAL);
    dispatch_async(queue, ^{
        NSMutableArray *arr = [self.imgBase64List mutableCopy];
        [self.imgDataList enumerateObjectsUsingBlock:^(NSData * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSString *base64String = [obj base64EncodedStringWithOptions:0];
            [arr addObject:base64String];
        }];
        self.imgBase64List = [arr copy];
        complete();
    });
}

- (void)p_requestImgDataWithAsset:(PHAsset *)asset complete:(void(^)(void))complete
{
    PHImageRequestOptions *option = [PHImageRequestOptions new];
    option.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
    
    [[PHImageManager defaultManager] requestImageDataForAsset:asset options:option resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
        
        NSMutableArray *arr = [self.imgDataList mutableCopy];
        [arr addObject:imageData];
        self.imgDataList = [arr copy];
        complete();
    }];
}

- (void)p_showTipEmptImgList
{
    [UIViewController showAelrtWithTitle:@"请先选择照片"];
}

- (void)p_initConfig
{
    self.imgViewList = @[];
    self.imgDataList = @[];
    self.imgIdList = @[];
    self.imgBase64List = @[];
    [self.p_view addImgList:@[self.addImg]];
}

- (void)p_presenetImgPickVC
{
    [self.pickImgHandle pickPhote];
}

- (void)p_deleteImg:(WBSelectResultImgView *)img
{
    NSMutableArray *arr = [self.imgViewList mutableCopy];
    [arr removeObject:img];
    self.imgViewList = [arr copy];
    [self p_apendAddImg];
    [self.p_view addImgList:self.imgViewList];
}

- (void)p_deleteImgId:(NSString *)imgId
{
    if(!imgId) return;
    
    NSMutableArray *arr = [self.imgIdList mutableCopy];
    [arr removeObject:imgId];
    self.imgIdList = [arr copy];
    [self.pickImgHandle updateImgIdList:self.imgIdList];
    [self p_resetData];
}

- (void)p_apendAddImg
{
    if(self.imgViewList.count == MAX_IMG_COUNT)return;
    if([self.imgViewList containsObject:self.addImg]) return;
    NSMutableArray *arr = [self.imgViewList mutableCopy];
    [arr addObject:self.addImg];
    self.imgViewList = [arr copy];
}

- (void)p_pickImageComplete:(NSArray <NSString *>*)imgIdList
{
    if(!imgIdList) return;
    if(imgIdList.count <= 0) return;
    
    self.imgIdList = imgIdList;
    
    NSMutableArray *arr = [@[] mutableCopy];
    
    [imgIdList enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        WBSelectResultImgView *imgView = [WBSelectResultImgView new];
        [arr addObject:imgView];
        
        [imgView loadImgId:obj];
        @WeakObj(self);
        @WeakObj(imgView);

        imgView.deleteBlock = ^{
            [selfWeak p_deleteImg:imgViewWeak];
            [selfWeak p_deleteImgId:imgViewWeak.imgId];
        };
        
    }];
    
    self.imgViewList = [arr copy];
    [self p_apendAddImg];
    [self.p_view addImgList:self.imgViewList];
}

//MARK: - get

- (WBImagesContainView *)p_view
{
    if(!_p_view){
        _p_view = [WBImagesContainView new];
    }
    return _p_view;
}

- (UIView *)view
{
    return self.p_view;
}

- (PickImageHandle *)pickImgHandle
{
    if(!_pickImgHandle){
        _pickImgHandle = [PickImageHandle new];
        _pickImgHandle.vc = [JXTool currentVC];
        _pickImgHandle.maxSelectImgCount = MAX_IMG_COUNT;
        
        @WeakObj(self);
        @WeakObj(_pickImgHandle);
        
        _pickImgHandle.complete = ^{
            @StrongObj(self);
            @StrongObj(_pickImgHandle)
            
            [self p_pickImageComplete:_pickImgHandle.imgIdList];
        };
    }
    return _pickImgHandle;
}

//MARK: - get

- (WBAddImgView *)addImg
{
    if(!_addImg){
        _addImg = [WBAddImgView new];
        @WeakObj(self);
        _addImg.addBlock = ^{
            @StrongObj(self);
            [self p_presenetImgPickVC];
        };
    }
    return _addImg;
}


@end
